package com.dongge.realm;

import com.dongge.entity.User;
import com.dongge.service.AuthorizationService;
import com.dongge.service.RoleService;
import com.dongge.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Set;

/**
 * Created by zhudong on 2016/8/17.
 */
@Repository("realm")
public class RealmAuth extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorizationService authorizationService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();
        Set<String> roleNames = roleService.getRoleNamesByUsername(username);
        Set<String> authorizationNames = authorizationService.getAuthorizationNamesByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleNames);
        simpleAuthorizationInfo.addStringPermissions(authorizationNames);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        if(!userService.login(username,password)){
            throw new UnknownAccountException("用户名或者密码错误");
        }
        return new SimpleAuthenticationInfo(username,password,getName());
    }
}
